package root.electronclass.electronclass.personal.activity

import android.annotation.SuppressLint
import android.content.res.ColorStateList
import android.os.Bundle
import android.view.View
import androidx.core.os.bundleOf
import androidx.core.text.bold
import androidx.core.text.buildSpannedString
import androidx.core.text.scale
import androidx.fragment.app.viewModels
import retrofit2.Call
import root.electronclass.electronclass.R
import root.electronclass.electronclass.common.base.BasicAdapter
import root.electronclass.electronclass.common.base.ViewBindingFragment
import root.electronclass.electronclass.databinding.ActivityAchievementBinding
import root.electronclass.electronclass.databinding.ItemAchievementBinding
import root.electronclass.electronclass.databinding.ItemFractionBinding
import root.electronclass.electronclass.ext.tabs
import root.electronclass.electronclass.mvp.GlobalParameter
import root.electronclass.electronclass.mvp.base.BaseResponse
import root.electronclass.electronclass.mvp.base.CallbackNext
import root.electronclass.electronclass.mvp.entity.ExamScoreRankVO
import root.electronclass.electronclass.mvp.entity.ExamSummary
import root.electronclass.electronclass.mvp.entity.StuExamScoreDetail
import root.electronclass.electronclass.mvp.rest.RestManager
import root.electronclass.electronclass.personal.activity.model.PersonModel
import root.electronclass.electronclass.personal.dialog.AchievementDetailDialog


class AchievementFragment : ViewBindingFragment<ActivityAchievementBinding>() {
    private val viewModel: PersonModel by viewModels()
    private var dataType = 1

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        val tabs = resources.getStringArray(R.array.person_tabs)
        binding.tabLayout.tabs(tabs) { tab ->
            when (tab) {
                getString(R.string.class_7_day) -> dataType = 1
                getString(R.string.class_3_month) -> dataType = 2
                getString(R.string.class_current_semester) -> dataType = 3
            }
            viewModel.load(dataType, 1)
        }
        binding.recycler.adapter = adapter
        binding.fractionRecycler.adapter = adapter1

        viewModel.data.observe(viewLifecycleOwner) {
            if (it.first == 1) {
                adapter.refresh(it.second)
                if (it.second.isNotEmpty()) {
                    binding.recycler.smoothScrollToPosition(0)
                }
            } else {
                adapter.addAll(it.second)
            }
        }
        showFirst()
    }

    private val adapter = BasicAdapter<ExamSummary, ItemAchievementBinding> { holder, item ->
        holder.binding.root.backgroundTintList = ColorStateList.valueOf(if (holder.adapterPosition % 2 == 0) 0 else 0xff7f8f9)
        holder.binding.name.text = item.title
        holder.binding.type.text = if (item.type == 0) "日常测验" else "统一考试"
        holder.binding.time.text = item.createTime
        holder.binding.created.text = item.creator
        holder.binding.detail.setOnClickListener {
            exmDetail(item.id)
        }
    }

    @SuppressLint("SetTextI18n")
    private val adapter1 = BasicAdapter<ExamScoreRankVO, ItemFractionBinding> { holder, item ->
        holder.binding.fraction.text = "${item.score}分"
        holder.binding.ranking1.text = buildSpannedString { scale(1.71f) { bold { item.classRank.toString() } }; append("\n班级排名") }
        holder.binding.ranking2.text = buildSpannedString { scale(1.71f) { bold { item.classRank.toString() } }; append("\n年级排名") }
        holder.binding.ranking3.text = buildSpannedString { scale(1.71f) { bold { item.classRank.toString() } }; append("\n全校排名") }
        holder.binding.subject.text = item.subject
        holder.binding.content.text = "较上次成绩${if (item.scoreUp < 0) "下降" else "上升"} ${item.scoreUp.toInt()}分"
        holder.binding.type.setBackgroundResource(if (item.scoreUp < 0) R.mipmap.decline else R.mipmap.icon_rise)
    }

    private fun showFirst() {
        RestManager.getInstance().initRest()
            .lastRankDetail(GlobalParameter.getEcardInfo().schoolId.toString(), GlobalParameter.getSTUDENT().id.toString())
            .enqueue(object : CallbackNext<BaseResponse<StuExamScoreDetail>>(mDialogViewModel) {
                override fun onSuccessful(
                    call: Call<BaseResponse<StuExamScoreDetail>>,
                    response: BaseResponse<StuExamScoreDetail>
                ) {
                    if (response.isSuccess) {
                        binding.tvExamination.text = response.rows.title
                        binding.tvExaminationType.text = if (response.rows.type == 0) "普考" else "统考"
                        adapter1.refresh(response.rows.list)
                    }
                }

                override fun onError(
                    call: Call<BaseResponse<StuExamScoreDetail>>?,
                    response: BaseResponse<StuExamScoreDetail>
                ) {
                    toast(response.msg)
                }

            })
    }

    private fun exmDetail(id: Int) {
        RestManager.getInstance().initRest().examDetail(id, GlobalParameter.getSTUDENT().id.toString())
            .enqueue(object : CallbackNext<BaseResponse<StuExamScoreDetail>>(mDialogViewModel) {
                override fun onSuccessful(
                    call: Call<BaseResponse<StuExamScoreDetail>>,
                    response: BaseResponse<StuExamScoreDetail>
                ) {
                    if (response.isSuccess) {
                        AchievementDetailDialog().also {
                            it.arguments = bundleOf(
                                AchievementDetailDialog.TITLE to "成绩详情",
                                AchievementDetailDialog.DATA to response.rows,
                            )
                        }.show(childFragmentManager, "CJXQ")
                    }
                }

                override fun onError(
                    call: Call<BaseResponse<StuExamScoreDetail>>?,
                    response: BaseResponse<StuExamScoreDetail>
                ) {
                    toast(response.msg)
                }

            })
    }
}